<template>
    <h2>商品信息</h2>
    <div style="text-align: left">
        <el-form :model="condForm" label-width="120px" :inline="true">
            <el-form-item><el-button type="primary" @click="openItemDialog">添加商品</el-button></el-form-item>
            <el-form-item label="编号">
                <el-input v-model="condForm.itemNum" readonly />
            </el-form-item>
            <el-form-item label="名称">
                <el-input v-model="condForm.itemName" />
            </el-form-item>
            <el-form-item label="状态" style="width: 25%;">
                <el-select v-model="condForm.statue" placeholder="请选择状态">
                    <el-option label="上架" value="0" />
                    <el-option label="下架" value="1" />
                    <el-option label="删除" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="queryItemList(currentPage)">查询</el-button>
            </el-form-item>
        </el-form>

    </div>
    <!-- 添加商品信息的对话框 -->
    <el-dialog v-model="dialogItemVisible" width="60%" :before-close="cleanForm">
        <div style="text-align: left">
            商品图片:<!--  上传商品图片控件  -->
            <el-upload action="http://localhost:8081/uploadImg" list-type="picture-card" :auto-upload="true"
                method="post" :on-success="handleAvatarSuccess">
                <el-icon>
                    <Plus />
                </el-icon>

                <template #file="{ file }">
                    <div>

                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                <el-icon><zoom-in /></el-icon>
                            </span>
                        </span>
                    </div>
                </template>
            </el-upload>
            <el-image v-for="img in imageUrls" :src="img" style="width: 138px;height: 138px"></el-image>
        </div>
        <el-form :model="itemForm" label-width="120px" :inline="true">

            <el-form-item label="名称">
                <el-input v-model="itemForm.itemName" />
            </el-form-item>
            <el-form-item label="编号">
                <el-input v-model="itemForm.itemNum" />
            </el-form-item>
            <el-form-item label="种类">
                <el-input v-model="itemForm.typeId" placeholder="请选择类型" @click="openTypeDialog" />
                <!-- <el-input v-model="itemForm.typeId" /> -->
            </el-form-item>
            <el-form-item label="库存">
                <el-input v-model="itemForm.store" />
            </el-form-item>
            <el-form-item label="品牌" style="width: 40%;">
                <el-select v-model="itemForm.brandId" class="m-2" placeholder="请选择供品牌">
                    <el-option v-for="item in brandList" :key="item.brandId" :label="item.brandName"
                        :value="item.brandId" />
                </el-select>
            </el-form-item>
            <el-form-item label="仓库" style="width: 40%;">
                <el-select v-model="itemForm.storeId" class="m-2" placeholder="请选择供仓库">
                    <el-option v-for="item in storeList" :key="item.storeId" :label="item.storeName"
                        :value="item.storeId" />
                </el-select>
            </el-form-item>
            <el-form-item label="供应商" style="width: 40%;">
                <el-select v-model="itemForm.supplyId" class="m-2" placeholder="请选择供应商" size="large">
                    <el-option v-for="item in supplyList" :key="item.supplyId" :label="item.supplyName"
                        :value="item.supplyId" />
                </el-select>
            </el-form-item>
            <el-form-item label="产地" style="width: 40%;">
                <el-select v-model="itemForm.placeId" class="m-2" placeholder="请选择供产地" size="large">
                    <el-option v-for="item in placeList" :key="item.placeId" :label="item.placeName"
                        :value="item.placeId" />
                </el-select>

            </el-form-item>
            <el-form-item label="单位" style="width: 40%;">
                <el-select v-model="itemForm.unitId" class="m-2" placeholder="请选择商品单位">
                    <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName"
                        :value="item.unitId" />
                </el-select>
            </el-form-item>
            <el-form-item label="进价">
                <el-input v-model="itemForm.price" />
            </el-form-item>
            <el-form-item label="售价">
                <el-input v-model="itemForm.sellPrice" />
            </el-form-item>
            <el-form-item label="会员价">
                <el-input v-model="itemForm.vipPrice" />
            </el-form-item>
            <el-form-item label="详细介绍" style="width: 100%">
                <el-input v-model="itemForm.itemDesc" type="text" />
            </el-form-item>
            <el-form-item label="生产日期">
                <el-date-picker v-model="itemForm.itemDate" type="date" placeholder="选择日期" :size="size" />

            </el-form-item>
            <el-form-item label="保质期">
                <el-date-picker v-model="itemForm.endDate" type="date" placeholder="选择日期" :size="size" />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogItemVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 图片预览的对话框 -->
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="图片预览" />
    </el-dialog>


    <el-dialog v-model="typeDialog" width="40%">
        <h2>选择商品类型</h2>
        <el-tree :props="config" :data="categoryList" default-expand-all node-key="id" ref="treeRef"
            :highlight-current="true" :expand-on-click-node="false" @node-click="handleClickNode">
        </el-tree>
        <el-button type="primary" @click="saveType">确认</el-button>
    </el-dialog>

    <el-table :data="itemList" :border="false" style="width: 100%">
        <el-table-column type="expand">
            <template #default="props">
                <div m="4">
                    <el-image :src="doImgs(props.row.imgs)" style="width: 200px;height: 100px"></el-image>

                    <el-table :data="[props.row]" :border="childBorder">
                        <el-table-column label="进价" prop="price" />
                        <el-table-column label="销售价" prop="sellPrice" />
                        <el-table-column label="会员价" prop="vipPrice" />
                        <el-table-column label="生产日期" prop="itemDate" />
                        <el-table-column label="过期日期" prop="endDate" />
                        <el-table-column label="库存" prop="store" />
                    </el-table>
                </div>
            </template>
        </el-table-column>
        <el-table-column label="编号" prop="itemNum" width="200" />
        <el-table-column label="名称" prop="itemName" />
        <el-table-column label="品牌" prop="brandName" />
        <el-table-column label="产地" prop="placeName" />
        <el-table-column label="状态">
            <template #default="scope">
                {{ toStatue(scope.row.statue) }}
            </template>
        </el-table-column>
        <el-table-column label="单位" prop="unitName" />
        <el-table-column fixed="right" label="操作" width="310%">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)">
                    修改
                </el-button>
                <el-button size="small" type="primary" @click="downItem(scope.row.id)">
                    下架
                </el-button>
                <el-button size="small" type="primary" @click="handleBuy(scope.row.id)">
                    采购
                </el-button>
                <el-button size="small" type="primary" @click="handleOut(scope.row.id)">
                    出货
                </el-button>

                <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination layout="prev, pager, next" :total="total" @current-change="queryItemList"
        v-model:current-page="currentPage" />


    <el-dialog v-model="buyDialog" width="60%" title="商品采购">

        <el-form :model="buyForm" label-width="120px">
            <el-form-item label="商品名称">
                {{ buyForm.itemName }}
            </el-form-item>
            <el-form-item label="仓库">
                {{ buyForm.storeName }}
            </el-form-item>
            <el-form-item label="供应商">
                {{ buyForm.supplyName }}
            </el-form-item>
            <el-form-item label="产地">
                {{ buyForm.placeName }}
            </el-form-item>
            <el-form-item label="预计采购量">
                <el-input v-model="buyForm.buyNum" style="width: 80%" />
            </el-form-item>
            <el-form-item label="采购人">
                <el-input v-model="buyForm.buyUser" style="width: 80%" />
            </el-form-item>

            <el-form-item label="采购人电话">
                <el-input v-model="buyForm.phone" style="width: 80%" />
            </el-form-item>


        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="buyDialog = false">取消</el-button>
                <el-button type="primary" @click="handleSaveBuy">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { Plus, ZoomIn } from '@element-plus/icons-vue'
import axios from "axios";
import { ElMessage } from "element-plus";
const size = ref('default')
const currentPage = ref(1)
const total = ref()

const childBorder = ref(false)

function handleSaveBuy() {
    axios.post("http://localhost:8081/saveBuyList", buyForm)
        .then((response) => {
            if (response.data.code == 200) {
                buyDialog.value = false;//关闭对话框
                //清空buyForm表单
                buyForm.productId = '';
                buyForm.itemName = "";
                buyForm.storeId = '';
                buyForm.storeName = '';
                buyForm.supplyId = '';
                buyForm.supplyName = '';
                buyForm.placeId = '';
                buyForm.placeName = '';
                buyForm.buyUser = '';
                buyForm.phone = '';
                buyForm.buyNum = '';;

                ElMessage.success(response.data.msg);
            } else {
                ElMessage.error(response.data.msg);
            }
        })
        .catch((error) => {
            console.log(error);
        })
}

const buyForm = reactive({
    productId: '',
    storeId: '',
    supplyId: '',
    placeId: '',
    itemName: '',
    storeName: '',
    supplyName: '',
    placeName: '',
    buyNum: '',
    buyUser: '',
    phone: ''
})

const buyDialog = ref(false)
function handleBuy(id) {
    console.log("=====" + id);
    buyDialog.value = true;
    //发送ajax请求，获得需要带入的数据
    axios.get("http://localhost:8081/buyAutoInfo/" + id)
        .then((resp) => {
            //获得响应数据对象
            var item = resp.data;
            //将响应数据赋值给buyForm表单
            buyForm.productId = item.id;
            buyForm.itemName = item.itemName;
            buyForm.storeId = item.storeId;
            buyForm.storeName = item.storeName;
            buyForm.supplyId = item.supplyId;
            buyForm.supplyName = item.supplyName;
            buyForm.placeId = item.placeId;
            buyForm.placeName = item.placeName;

        })
        .catch((error) => {
            console.log(error);
        });
}

function handleEdit(row) {

    dialogItemVisible.value = true
    url = "http://localhost:8081/updateItem"
    loadSupplyList()
    loadPlaceList()
    queryUnitList()
    queryBrandList()
    queryStoreList()

    imageUrls.value = row.imgs.split(",")
    itemForm.imgArr = row.imgs.split(",")

    itemForm.id = row.id;
    itemForm.itemNum = row.itemNum;
    itemForm.itemName = row.itemName;
    itemForm.typeId = row.typeId;
    itemForm.placeId = row.placeId;
    itemForm.brandId = row.brandId;
    itemForm.supplyId = row.supplyId;
    itemForm.storeId = row.storeId;
    itemForm.itemDesc = row.itemDesc;
    itemForm.itemDate = row.itemDate;
    itemForm.endDate = row.endDate;
    itemForm.price = row.price;
    itemForm.store = row.store
    itemForm.sellPrice = row.sellPrice;
    itemForm.vipPrice = row.vipPrice;
    itemForm.unitId = row.unitId;
}

var url = ''
const imgUrl = ref(null)
const imageUrls = ref([])
function cleanForm() {
    console.log("cancel")
    Object.assign(itemForm, {
        id: '',
        itemNum: '',
        itemName: '',
        typeId: '',
        store: 0,
        brandId: '',
        storeId: '',
        supplyId: '',
        placeId: '',
        unitId: '',
        price: '0.0',
        sellPrice: 0.0,
        vipPrice: '',
        itemDesc: '',
        itemDate: '',
        endDate: '',
        imgs: '',
        imgArr: []
    })

    imageUrls.value = null

    dialogItemVisible.value = false
}

function handleDelete(id) {
    axios.get("http://localhost:8081/deleteItem/" + id)
        .then((response) => {
            if (response.data.code == 200) {
                //刷新列表
                queryItemList(currentPage);
                ElMessage.success(response.data.msg);
            } else {
                ElMessage.error(response.data.msg);
            }
        })
        .catch((error) => {
            console.log(error);
        })
}

function downItem(id) {
    axios.get("http://localhost:8081/downItem/" + id)
        .then((response) => {
            if (response.data.code == 200) {
                //刷新列表
                queryItemList(currentPage);
                ElMessage.success(response.data.msg);
            } else {
                ElMessage.error(response.data.msg);
            }
        })
        .catch((error) => {
            console.log(error);
        })
}

const condForm = reactive({
    itemNum: '',
    itemName: '',
    statue: ''
});

const itemList = ref([])
function queryItemList(pageNum) {
    condForm.pageNum = pageNum;
    axios.post("http://localhost:8081/itemList", condForm)
        .then((resp) => {
            itemList.value = resp.data.items;
            total.value = resp.data.total;
        })
        .catch((error) => {
            console.log(error);
        })
}

function toStatue(statue) {
    switch (statue) {
        case 0:
            return "上架";
        case 1:
            return "下架";
        case 2:
            return "删除";
    }
}

function doImgs(path) {

    return (path + "").split(",")[0];

}

onMounted(() => {
    queryItemList(1)
})

const itemForm = reactive({
    id: '',
    itemNum: '',
    itemName: '',
    typeId: '',
    store: 0,
    brandId: '',
    storeId: '',
    supplyId: '',
    placeId: '',
    unitId: '',
    price: '0.0',
    sellPrice: 0.0,
    vipPrice: '',
    itemDesc: '',
    itemDate: '',
    endDate: '',
    imgs: '',
    imgArr: []
})

//声明tree的配置
const config = {
    id: 'id',
    label: 'label',
    children: 'children'
};
//声明tree的引用
const treeRef = ref(null);
//声明树节点数据
const categoryList = ref([]);
//发送请求加载树
function itemCategoryTree() {
    axios.get("http://localhost:8081/categoryList")
        .then((response) => {
            categoryList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        })
}
//发送请求提交form表单
function onSave() {
    itemForm.imgs = itemForm.imgArr.toString()
    console.log(itemForm)
    axios.post(url, itemForm)
        .then((resp) => {
            if (resp.data.code == 200) {
                dialogItemVisible.value = false; //关闭对话框
                cleanForm()
                ElMessage.success(resp.data.msg);
                queryItemList(currentPage.value)
            } else {
                ElMessage.error(resp.data.msg);
            }
        })
        .catch((error) => {
            console.log(error);
        })
}
var pnode = null;//记录当前选中的节点对象
//树节点单击的回调函数
function handleClickNode(node, data) {
    pnode = node;
}
//当选择某个类型节点确认关闭对话框
function saveType() {
    if (!(pnode && pnode.children.length == 0)) {
        ElMessage.warning("必选选中叶子节点........");
        return;
    }
    typeDialog.value = false;
    itemForm.typeId = pnode.id;


}

//定义选择商品类目的对话框状态
function openTypeDialog() {
    typeDialog.value = true;
    itemCategoryTree();//打开对话框显示类目树
}

//声明仓库列表集合
const storeList = ref([])
function queryStoreList() {
    axios.get("http://localhost:8081/storeList")
        .then((response) => {
            storeList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        });
}

//声明品牌选项集合
const brandList = ref([]);
function queryBrandList() {
    axios.get("http://localhost:8081/brandList")
        .then((response) => {
            brandList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        });
}

//声明单位集合
const unitList = ref([]);
function queryUnitList() {
    axios.get("http://localhost:8081/unitList")
        .then((response) => {
            unitList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        });
}

const placeList = ref([]);
function loadPlaceList() {
    axios.get("http://localhost:8081/placeList")
        .then((response) => {
            placeList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        });
}

const supplyList = ref([]);
function loadSupplyList() {
    axios.get("http://localhost:8081/supplyList")
        .then((response) => {
            supplyList.value = response.data;
        })
        .catch((error) => {
            console.log(error);
        })
}

//定义对话框状态
const dialogItemVisible = ref(false);
const typeDialog = ref(false)

function getItemCode() {
    axios.get("http://localhost:8081/getCode").then((resp) => {
        itemForm.itemNum = resp.data
    }).catch((error) => {
        console.log(error)
    })
}

//定义函数打开添加商品对话框
function openItemDialog() {
    url = "http://localhost:8081/addItem"
    dialogItemVisible.value = true
    loadSupplyList()
    loadPlaceList()
    queryUnitList()
    queryBrandList()
    queryStoreList()
    getItemCode()
}

//声明变量保存需要预览的图片路径
const dialogImageUrl = ref(null);
//预览图片对话框的状态
const dialogVisible = ref(false);
function handlePictureCardPreview(file) {
    console.log("======================" + file);
    dialogImageUrl.value = file.url;
    dialogVisible.value = true
}
//定义图片上传成功后的回调函数
function handleAvatarSuccess(path) {
    console.log(path)
    itemForm.imgArr = []
    itemForm.imgArr.push(path)
    imageUrls.value = null
}
</script>

<style scoped></style>